package com.atguigu.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCode;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.hosp.client.ScheduleFeignClient;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.order.mapper.OrderInfoMapper;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.WxPayService;
import com.atguigu.yygh.order.utils.HttpRequestHelper;
import com.atguigu.yygh.rabbit.config.MQConst;
import com.atguigu.yygh.rabbit.service.RabbitService;
import com.atguigu.yygh.user.client.PatientFeignClient;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.atguigu.yygh.vo.sms.SmsVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2023-01-06
 */
@Service
@Slf4j
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
    @Autowired
    private PatientFeignClient patientFeignClient;
    @Autowired
    private ScheduleFeignClient scheduleFeignClient;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private RabbitService rabbitService;


    /**
     * 获取订单列表
     *
     * @return
     */
    @Override
    public List<OrderInfo> selectList(Long userId) {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
        orderInfoList.stream().forEach(this::packOrderInfo);
        return orderInfoList;
    }

    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        return this.packOrderInfo(orderInfo);
    }

    private OrderInfo packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }

    /**
     * 创建订单
     *
     * @param scheduleId
     * @param patientId
     * @return
     */
    @Override
    public Long submitOrder(String scheduleId, Long patientId, Long userId) {

        //创建订单对象
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);

        //step1：基本信息
        //时间戳+随机数      System.currentTimeMillis()
        String outTradeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo); //订单号
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());//未支付

        //step2：就诊人数据：远程获取就诊人数据（openfeign）
        Patient patient = patientFeignClient.getPatient(patientId);
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setPatientName(patient.getName());
        orderInfo.setUserId(patient.getUserId());


        //step3：获取医院排班相关数据
        ScheduleOrderVo scheduleOrderVo = scheduleFeignClient.getScheduleOrderVo(scheduleId);
        orderInfo.setScheduleId(scheduleId);
        BeanUtils.copyProperties(scheduleOrderVo, orderInfo);//拷贝相关属性


        //step4：调用医院端接口获取相关数据
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("hoscode", scheduleOrderVo.getHoscode());
        paramsMap.put("depcode", scheduleOrderVo.getDepcode());
        paramsMap.put("hosScheduleId", scheduleOrderVo.getHosScheduleId());
        paramsMap.put("reserveDate", new DateTime(scheduleOrderVo.getReserveDate()).toString("yyyy-MM-dd"));
        paramsMap.put("reserveTime", scheduleOrderVo.getReserveTime());
        paramsMap.put("amount", scheduleOrderVo.getAmount());
        paramsMap.put("name", patient.getName());
        paramsMap.put("certificatesType", patient.getCertificatesType());
        paramsMap.put("certificatesNo", patient.getCertificatesNo());
        paramsMap.put("sex", patient.getSex());
        paramsMap.put("birthdate", patient.getBirthdate());
        paramsMap.put("phone", patient.getPhone());
        paramsMap.put("isMarry", patient.getIsMarry());
        paramsMap.put("timestamp", HttpRequestHelper.getTimestamp());

        //远程获取医院端的sign_key TODO  8e4bb4b497c3b1af4959bed2389c5acf
        String signKey = "c241f851124077d736415206ace167cb";
        paramsMap.put("sign", HttpRequestHelper.getSign(paramsMap, signKey));//标准签名

        //远程获取医院端的接口主机 TODO http://localhost:9998
        String apiHost = "http://localhost:9998"; //TODO
        JSONObject jsonResult = HttpRequestHelper.sendRequest(paramsMap, apiHost + "/order/submitOrder");
        if (jsonResult.getInteger("code").equals(ResultCodeEnum.SUCCESS.getCode())) {//成功

            JSONObject data = jsonResult.getJSONObject("data");
            String hosRecordId = data.getString("hosRecordId");
            Integer number = data.getInteger("number");
            String fetchTime = data.getString("fetchTime");
            String fetchAddress = data.getString("fetchAddress");
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.insert(orderInfo);

            //使用这两个数据更新平台端的最新的排班数量
            Integer reservedNumber = data.getInteger("reservedNumber");
            Integer availableNumber = data.getInteger("availableNumber");

            // 目的1：更新mongodb数据库中的排班数量
            // TODO 中间件：MQ 异步解耦
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setAvailableNumber(availableNumber);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setScheduleId(scheduleId);
            // 发消息
            rabbitService.sendMessage(MQConst.EXCHANGE_DIRECT_ORDER, MQConst.ROUTING_ORDER, orderMqVo);
            // 组装消息对象
            SmsVo smsVo = new SmsVo();
            smsVo.setPhone(orderInfo.getPatientPhone());
            //亲爱的用户：您已预约${title}就诊
            //请您于${fetchTime}，至${fetchAddress}取号，
            //您的号码是${number}，请您及时就诊
            smsVo.setTemplateCode("TP12345678");
            HashMap<String, Object> params = new HashMap<>();
            params.put("title", orderInfo.getHosname() + orderInfo.getDepname() + new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午"));
            params.put("fetchTime", orderInfo.getFetchTime());
            params.put("fetchAddress", orderInfo.getFetchAddress());
            params.put("number", orderInfo.getNumber());
            smsVo.setParam(params);
            //目的2：给就诊人发短信 TODO：MQ
            //向MQ发消息
            rabbitService.sendMessage(MQConst.EXCHANGE_DIRECT_SMS, MQConst.ROUTING_SMS, smsVo);
            return orderInfo.getId(); //返回订单id
        } else {
            log.error("预约失败，"
                    + "code：" + jsonResult.getInteger("code")
                    + "，message：" + jsonResult.getString("message")
            );
            throw new YyghException(ResultCode.ERROR, "预约失败");
        }


    }

    /**
     * 就医提醒
     */
    @Override
    public void patientTips() {

        //查询今天的预约信息
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reserve_date", new DateTime().toString("yyyy-MM-dd"));
        //未取消
        queryWrapper.ne("order_status", OrderStatusEnum.CANCLE.getStatus());
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);

        for (OrderInfo orderInfo : orderInfoList) {

            //短信对象
            SmsVo smsVo = new SmsVo();
            smsVo.setPhone(orderInfo.getPatientPhone());
            smsVo.setTemplateCode("TP12345678");
            //亲爱的用户${name}，您预约了${reserveDate}在${title}的就诊，请及时就医
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<>();
            param.put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
            param.put("reserveDate", reserveDate);
            param.put("name", orderInfo.getPatientName());
            smsVo.setParam(param);

            //发消息
            rabbitService.sendMessage(MQConst.EXCHANGE_DIRECT_SMS, MQConst.ROUTING_SMS, smsVo);
        }
    }

    @Override
    public void cancelOrder(Long orderId) {

        // 只要未支付就可以无条件取消预约，
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        // TODO 判断是否已退款，如果已经退款 则推出

        // 判断订单是否支付
        if (orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()) {
            // 判断退号时间
            //当前时间大约退号时间，不能取消预约
            DateTime quitTime = new DateTime(orderInfo.getQuitTime());
            if (quitTime.isBeforeNow()) {
                throw new YyghException(ResultCode.ERROR, "已过退号时间，无法取消");
            }
            // 退款
            log.info("退款");
            wxPayService.refund(orderId);

        }

        String signKey = "c241f851124077d736415206ace167cb";
        Map<String, Object> params = new HashMap<>();
        params.put("hoscode", orderInfo.getHoscode());
        params.put("hosRecordId", orderInfo.getHosRecordId());
        params.put("hosScheduleId", orderInfo.getHosScheduleId());
        params.put("timestamp", HttpRequestHelper.getTimestamp());
        params.put("sign", HttpRequestHelper.getSign(params, signKey));//略：处理方式同前面方案
        JSONObject result = HttpRequestHelper.sendRequest(params, "http://localhost:9998/order/updateCancelStatus");

        if (!result.getInteger("code").equals(ResultCodeEnum.SUCCESS.getCode())) {
            throw new YyghException(ResultCode.ERROR, "取消订单失败");
        }
        // 然后修改统一平台的订单状态
        this.updateStatusById(orderId, OrderStatusEnum.CANCLE.getStatus());


        // 得到返回数据
        JSONObject jsonObject = result.getJSONObject("data");
        Integer reservedNumber = jsonObject.getInteger("reservedNumber");
        Integer availableNumber = jsonObject.getInteger("availableNumber");

        //  根据医院端返回的数据（mysql），更新平台端的排班数据（mongodb）
        OrderMqVo orderMqVo = new OrderMqVo();
        orderMqVo.setScheduleId(orderInfo.getScheduleId());
        //从医院接口中返回的数据中获取
        //因为医院端的接口尚不完善，没有返回需要的最新的余号数据，因此此处硬编码重置平台端的余号数据
        orderMqVo.setAvailableNumber(availableNumber);
        orderMqVo.setReservedNumber(reservedNumber);
        rabbitService.sendMessage(MQConst.EXCHANGE_DIRECT_ORDER, MQConst.ROUTING_ORDER, orderMqVo);

        //给就诊人发送短信
        //组装消息对象
        SmsVo smsVo = new SmsVo();
        smsVo.setPhone(orderInfo.getPatientPhone());
        smsVo.setTemplateCode("TP12345679");
        //亲爱的用户：您已取消${title}就诊
        HashMap<String, Object> paramsSms = new HashMap<>();
        paramsSms.put("title",
                orderInfo.getHosname() +
                        orderInfo.getDepname() +
                        new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") +
                        (orderInfo.getReserveTime() == 0 ? "上午" : "下午"));
        smsVo.setParam(paramsSms);

        //向MQ发消息
        rabbitService.sendMessage(MQConst.EXCHANGE_DIRECT_SMS, MQConst.ROUTING_SMS, smsVo);

    }

    /**
     * 根据订单id更新订单状态
     *
     * @param orderId
     * @param status
     */
    @Override
    public void updateStatusById(Long orderId, Integer status) {

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setId(orderId);
        orderInfo.setOrderStatus(status);
        baseMapper.updateById(orderInfo);
    }


}
